<template>
  <div class="code-mapping p-4">
    <!-- 顶部横幅 -->
    <div class="overview-banner mb-6 bg-gradient-to-r from-green-500 to-green-700 text-white rounded-lg shadow-lg p-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold mb-2">代码标准映射管理</h1>
          <p class="opacity-80">管理不同系统之间的代码映射关系，实现系统间代码值转换</p>
        </div>
        <div class="flex space-x-4">
          <el-button type="primary" plain @click="handleAdd">
            <div class="i-carbon-add mr-1"></div>新增映射关系
          </el-button>
          <el-button type="primary" plain @click="handleExport">
            <div class="i-carbon-export mr-1"></div>导出映射
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-container mb-6 bg-white p-4 rounded-lg shadow-md">
      <el-form :model="queryParams" inline>
        <el-form-item label="标准代码">
          <el-select 
            v-model="queryParams.standardCode" 
            placeholder="请选择标准代码" 
            clearable
            filterable
            class="w-52"
          >
            <el-option
              v-for="item in codeStandardOptions"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统">
          <el-select 
            v-model="queryParams.systemId" 
            placeholder="请选择系统" 
            clearable
            filterable
            class="w-40"
          >
            <el-option
              v-for="item in systemOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="映射状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="w-32">
            <el-option label="已映射" :value="1" />
            <el-option label="未映射" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容展示区域 -->
    <div class="content-container mb-6 grid grid-cols-5 gap-6">
      <!-- 左侧代码标准详情 -->
      <div class="col-span-2 bg-white p-4 rounded-lg shadow-md">
        <div class="text-lg font-bold mb-4">标准代码详情</div>
        <template v-if="activeStandardCode">
          <div class="mb-4">
            <ArtDataListCard title="基本信息" :list="[
              { label: '代码', value: activeStandardCode.code },
              { label: '名称', value: activeStandardCode.name },
              { label: '分类', value: activeStandardCode.categoryName },
              { label: '描述', value: activeStandardCode.description || '无' },
              { label: '状态', value: activeStandardCode.status ? '启用' : '禁用' }
            ]" />
          </div>
          
          <div class="text-base font-medium mb-2">标准代码值</div>
          <el-table :data="standardValues" border stripe max-height="300">
            <el-table-column prop="code" label="编码" width="60" />
            <el-table-column prop="name" label="名称" min-width="150" />
            <el-table-column prop="value" label="值" width="80" />
            <el-table-column prop="sort" label="排序" width="60" />
          </el-table>
        </template>
        <div v-else class="text-center text-gray-500 py-10">请选择标准代码查看详情</div>
      </div>

      <!-- 右侧映射列表 -->
      <div class="col-span-3 bg-white p-4 rounded-lg shadow-md">
        <div class="flex justify-between mb-4">
          <div class="text-lg font-bold">映射关系列表</div>
          <div class="text-sm text-gray-500">
            未映射: <span class="text-red-500 font-bold mr-2">{{ unmappedCount }}</span>
            已映射: <span class="text-green-500 font-bold">{{ totalCount - unmappedCount }}</span>
          </div>
        </div>

        <ArtTable
          :data="tableData"
          :loading="loading"
          :border="true"
          :stripe="true"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <el-table-column prop="standardCode" label="标准代码" width="100" />
          <el-table-column prop="standardName" label="标准名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="standardValue" label="标准值" width="80" />
          <el-table-column prop="systemName" label="系统名称" width="100" />
          <el-table-column prop="systemCode" label="系统代码" width="100" />
          <el-table-column prop="systemCodeValue" label="系统值" width="80" />
          <el-table-column prop="systemCodeName" label="系统显示名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="status" label="映射状态" width="90">
            <template #default="scope">
              <el-tag :type="scope.row.mappingStatus ? 'success' : 'danger'">
                {{ scope.row.mappingStatus ? '已映射' : '未映射' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button 
                size="small" 
                :type="scope.row.mappingStatus ? 'info' : 'primary'" 
                @click="handleEditMapping(scope.row)"
              >
                {{ scope.row.mappingStatus ? '修改映射' : '建立映射' }}
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteMapping(scope.row)"
                v-if="scope.row.mappingStatus"
              >
                解除
              </el-button>
            </template>
          </el-table-column>
        </ArtTable>
      </div>
    </div>

    <!-- 数据分析区域 -->
    <div class="analysis-container grid grid-cols-2 gap-6">
      <!-- 系统映射覆盖率 -->
      <div class="bg-white p-4 rounded-lg shadow-md">
        <div class="text-lg font-bold mb-4">系统映射覆盖率</div>
        <div class="h-72" ref="coverageChartRef"></div>
      </div>

      <!-- 映射趋势 -->
      <div class="bg-white p-4 rounded-lg shadow-md">
        <div class="text-lg font-bold mb-4">映射趋势</div>
        <div class="h-72" ref="trendChartRef"></div>
      </div>
    </div>

    <!-- 映射关系编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改映射关系' : '新增映射关系'"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="标准代码" prop="standardCode">
          <el-select 
            v-model="form.standardCode"
            placeholder="请选择标准代码"
            filterable
            class="w-full"
            :disabled="isEdit"
            @change="handleStandardCodeChange"
          >
            <el-option
              v-for="item in codeStandardOptions"
              :key="item.id"
              :label="`${item.name} (${item.code})`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标准代码值" prop="standardValue">
          <el-select 
            v-model="form.standardValue"
            placeholder="请选择标准代码值"
            filterable
            class="w-full"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in standardValueOptions"
              :key="item.code"
              :label="`${item.name} (${item.value})`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统" prop="systemId">
          <el-select 
            v-model="form.systemId"
            placeholder="请选择系统"
            filterable
            class="w-full"
            :disabled="isEdit"
            @change="handleSystemChange"
          >
            <el-option
              v-for="item in systemOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统代码" prop="systemCode">
          <el-select 
            v-model="form.systemCode"
            placeholder="请选择系统代码"
            filterable
            class="w-full"
            :disabled="isEdit"
            @change="handleSystemCodeChange"
          >
            <el-option
              v-for="item in systemCodeOptions"
              :key="item.code"
              :label="`${item.name} (${item.code})`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统代码值" prop="systemCodeValue">
          <el-select 
            v-model="form.systemCodeValue"
            placeholder="请选择系统代码值"
            filterable
            class="w-full"
          >
            <el-option
              v-for="item in systemValueOptions"
              :key="item.code"
              :label="`${item.name} (${item.code})`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="映射描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入映射描述" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import ArtTable from '@/components/core/tables/ArtTable.vue'
import ArtDataListCard from '@/components/core/cards/ArtDataListCard.vue'

const route = useRoute()

// 数据加载和分页
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalCount = ref(100)
const unmappedCount = ref(23)

// 查询参数
const queryParams = reactive({
  standardCode: '',
  systemId: '',
  status: ''
})

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({
  id: '',
  standardCode: '',
  standardValue: '',
  systemId: '',
  systemCode: '',
  systemCodeValue: '',
  description: ''
})

// 验证规则
const rules = {
  standardCode: [{ required: true, message: '请选择标准代码', trigger: 'change' }],
  standardValue: [{ required: true, message: '请选择标准代码值', trigger: 'change' }],
  systemId: [{ required: true, message: '请选择系统', trigger: 'change' }],
  systemCode: [{ required: true, message: '请选择系统代码', trigger: 'change' }],
  systemCodeValue: [{ required: true, message: '请选择系统代码值', trigger: 'change' }]
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    standardCode: 'GENDER',
    standardName: '性别代码',
    standardValue: '1',
    standardValueName: '男',
    systemName: '人事系统',
    systemCode: 'SEX',
    systemCodeValue: 'M',
    systemCodeName: '男',
    mappingStatus: 1
  },
  {
    id: 2,
    standardCode: 'GENDER',
    standardName: '性别代码',
    standardValue: '2',
    standardValueName: '女',
    systemName: '人事系统',
    systemCode: 'SEX',
    systemCodeValue: 'F',
    systemCodeName: '女',
    mappingStatus: 1
  },
  {
    id: 3,
    standardCode: 'GENDER',
    standardName: '性别代码',
    standardValue: '9',
    standardValueName: '未知',
    systemName: '人事系统',
    systemCode: 'SEX',
    systemCodeValue: 'U',
    systemCodeName: '未知',
    mappingStatus: 1
  },
  {
    id: 4,
    standardCode: 'GENDER',
    standardName: '性别代码',
    standardValue: '1',
    standardValueName: '男',
    systemName: '学籍系统',
    systemCode: 'XB',
    systemCodeValue: '1',
    systemCodeName: '男',
    mappingStatus: 1
  },
  {
    id: 5,
    standardCode: 'GENDER',
    standardName: '性别代码',
    standardValue: '2',
    standardValueName: '女',
    systemName: '学籍系统',
    systemCode: 'XB',
    systemCodeValue: '2',
    systemCodeName: '女',
    mappingStatus: 1
  },
  {
    id: 6,
    standardCode: 'NATION',
    standardName: '民族代码',
    standardValue: '01',
    standardValueName: '汉族',
    systemName: '人事系统',
    systemCode: 'NATION',
    systemCodeValue: null,
    systemCodeName: null,
    mappingStatus: 0
  }
])

// 下拉选项
const codeStandardOptions = ref([
  { id: 1, code: 'GENDER', name: '性别代码', categoryName: '通用基础' },
  { id: 2, code: 'NATION', name: '民族代码', categoryName: '通用基础' },
  { id: 3, code: 'EDU_LEVEL', name: '教育程度', categoryName: '教育相关' }
])

const systemOptions = ref([
  { id: 1, name: '人事系统', code: 'HR' },
  { id: 2, name: '学籍系统', code: 'STU' },
  { id: 3, name: '财务系统', code: 'FIN' }
])

const standardValueOptions = ref([])
const systemCodeOptions = ref([])
const systemValueOptions = ref([])

// 当前选中的标准代码
const activeStandardCode = ref(null)
// 当前选中的标准代码值列表
const standardValues = ref([
  { code: '1', name: '男', value: 'M', sort: 1 },
  { code: '2', name: '女', value: 'F', sort: 2 },
  { code: '9', name: '未知', value: 'U', sort: 9 }
])

// 图表引用
const coverageChartRef = ref()
const trendChartRef = ref()
let coverageChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// 处理标准代码变化
const handleStandardCodeChange = (code) => {
  form.standardValue = ''
  // 根据选择的标准代码加载对应的标准值选项
  const selectedStandard = codeStandardOptions.value.find(item => item.code === code)
  if (selectedStandard) {
    // 模拟加载标准值选项
    if (code === 'GENDER') {
      standardValueOptions.value = [
        { code: '1', name: '男', value: 'M' },
        { code: '2', name: '女', value: 'F' },
        { code: '9', name: '未知', value: 'U' }
      ]
    } else if (code === 'NATION') {
      standardValueOptions.value = [
        { code: '01', name: '汉族', value: '01' },
        { code: '02', name: '蒙古族', value: '02' },
        { code: '03', name: '回族', value: '03' }
      ]
    } else {
      standardValueOptions.value = []
    }
  }
}

// 处理系统变化
const handleSystemChange = (systemId) => {
  form.systemCode = ''
  form.systemCodeValue = ''
  // 根据选择的系统加载对应的系统代码选项
  const selectedSystem = systemOptions.value.find(item => item.id === systemId)
  if (selectedSystem) {
    // 模拟加载系统代码选项
    if (systemId === 1) { // 人事系统
      systemCodeOptions.value = [
        { code: 'SEX', name: '性别代码' },
        { code: 'NATION', name: '民族代码' }
      ]
    } else if (systemId === 2) { // 学籍系统
      systemCodeOptions.value = [
        { code: 'XB', name: '性别' },
        { code: 'MZ', name: '民族' }
      ]
    } else {
      systemCodeOptions.value = []
    }
  }
}

// 处理系统代码变化
const handleSystemCodeChange = (code) => {
  form.systemCodeValue = ''
  // 根据选择的系统代码加载对应的系统值选项
  if (code === 'SEX') {
    systemValueOptions.value = [
      { code: 'M', name: '男', value: 'M' },
      { code: 'F', name: '女', value: 'F' },
      { code: 'U', name: '未知', value: 'U' }
    ]
  } else if (code === 'XB') {
    systemValueOptions.value = [
      { code: '1', name: '男', value: '1' },
      { code: '2', name: '女', value: '2' }
    ]
  } else if (code === 'NATION' || code === 'MZ') {
    systemValueOptions.value = [
      { code: '01', name: '汉族', value: '01' },
      { code: '02', name: '蒙古族', value: '02' },
      { code: '03', name: '回族', value: '03' }
    ]
  } else {
    systemValueOptions.value = []
  }
}

// 获取映射列表
const getList = () => {
  loading.value = true
  setTimeout(() => {
    // 模拟筛选数据
    const filteredData = tableData.value.filter(item => {
      const matchStandardCode = !queryParams.standardCode || 
        item.standardCode === queryParams.standardCode
      
      const matchSystemId = !queryParams.systemId || 
        (queryParams.systemId === 1 && item.systemName === '人事系统') ||
        (queryParams.systemId === 2 && item.systemName === '学籍系统')
      
      const matchStatus = queryParams.status === '' || 
        item.mappingStatus === queryParams.status
      
      return matchStandardCode && matchSystemId && matchStatus
    })
    
    total.value = filteredData.length
    tableData.value = filteredData
    
    // 如果选择了标准代码，加载详情
    if (queryParams.standardCode) {
      const selectedStandard = codeStandardOptions.value.find(item => item.code === queryParams.standardCode)
      if (selectedStandard) {
        activeStandardCode.value = selectedStandard
        
        // 加载标准代码值
        if (queryParams.standardCode === 'GENDER') {
          standardValues.value = [
            { code: '1', name: '男', value: 'M', sort: 1 },
            { code: '2', name: '女', value: 'F', sort: 2 },
            { code: '9', name: '未知', value: 'U', sort: 9 }
          ]
        } else if (queryParams.standardCode === 'NATION') {
          standardValues.value = [
            { code: '01', name: '汉族', value: '01', sort: 1 },
            { code: '02', name: '蒙古族', value: '02', sort: 2 },
            { code: '03', name: '回族', value: '03', sort: 3 }
          ]
        }
      }
    } else {
      activeStandardCode.value = null
    }
    
    loading.value = false
  }, 500)
}

// 重置查询条件
const resetQuery = () => {
  queryParams.standardCode = ''
  queryParams.systemId = ''
  queryParams.status = ''
  activeStandardCode.value = null
  getList()
}

// 初始化覆盖率图表
const initCoverageChart = () => {
  if (!coverageChartRef.value) return
  
  coverageChart = echarts.init(coverageChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 'bottom',
      data: ['人事系统', '学籍系统', '财务系统', '其他系统']
    },
    series: [
      {
        name: '映射覆盖率',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 85, name: '人事系统' },
          { value: 75, name: '学籍系统' },
          { value: 60, name: '财务系统' },
          { value: 40, name: '其他系统' }
        ]
      }
    ]
  }
  
  coverageChart.setOption(option)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['已映射', '未映射'],
      bottom: 'bottom'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '已映射',
        type: 'line',
        data: [50, 60, 70, 75, 80, 85],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '未映射',
        type: 'line',
        data: [50, 40, 30, 25, 20, 15],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#F56C6C'
        },
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 窗口大小变化时重新绘制图表
const handleResize = () => {
  coverageChart?.resize()
  trendChart?.resize()
}

// 新增映射关系
const handleAdd = () => {
  isEdit.value = false
  form.id = ''
  form.standardCode = queryParams.standardCode || ''
  form.standardValue = ''
  form.systemId = queryParams.systemId || ''
  form.systemCode = ''
  form.systemCodeValue = ''
  form.description = ''
  
  if (form.standardCode) {
    handleStandardCodeChange(form.standardCode)
  }
  
  if (form.systemId) {
    handleSystemChange(form.systemId)
  }
  
  dialogVisible.value = true
}

// 编辑映射关系
const handleEditMapping = (row) => {
  isEdit.value = true
  form.id = row.id
  form.standardCode = row.standardCode
  form.standardValue = row.standardValue
  form.systemId = row.systemName === '人事系统' ? 1 : 
    row.systemName === '学籍系统' ? 2 : 
    row.systemName === '财务系统' ? 3 : null
  form.systemCode = row.systemCode
  form.systemCodeValue = row.systemCodeValue
  form.description = row.description || ''
  
  // 加载相关选项
  handleStandardCodeChange(form.standardCode)
  handleSystemChange(form.systemId)
  handleSystemCodeChange(form.systemCode)
  
  dialogVisible.value = true
}

// 删除映射关系
const handleDeleteMapping = (row) => {
  ElMessageBox.confirm(`确认解除"${row.standardName}"与"${row.systemName}"的映射关系吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 执行解除映射逻辑
    row.mappingStatus = 0
    row.systemCodeValue = null
    row.systemCodeName = null
    unmappedCount.value++
    ElMessage.success('解除映射成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  const formRef = ref(null)
  formRef.value?.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 修改映射
        ElMessage.success('修改映射关系成功')
      } else {
        // 新增映射
        ElMessage.success('新增映射关系成功')
        unmappedCount.value = Math.max(0, unmappedCount.value - 1)
      }
      dialogVisible.value = false
      getList()
    }
  })
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getList()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getList()
}

// 初始化
onMounted(() => {
  // 检查是否从标准代码管理页面跳转过来
  if (route.query.code) {
    queryParams.standardCode = route.query.code as string
    activeStandardCode.value = {
      id: route.query.id,
      code: route.query.code,
      name: route.query.name,
      categoryName: '通用基础',
      status: 1,
      description: ''
    }
  }
  
  getList()
  initCoverageChart()
  initTrendChart()
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  coverageChart?.dispose()
  trendChart?.dispose()
})
</script>

<style scoped lang="scss">
.code-mapping {
  .overview-banner {
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: -50%;
      right: -50%;
      width: 100%;
      height: 200%;
      background-image: linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.1) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.1) 50%,
        rgba(255, 255, 255, 0.1) 75%,
        transparent 75%,
        transparent
      );
      background-size: 20px 20px;
      transform: rotate(25deg);
      z-index: 1;
    }
  }
}
</style> 